<template>
  <div id="discuss">
    <div class="discuss-btn">
      <el-button @click="dialogVisible = true" size="default" type="primary">贡献题解</el-button>
    </div>
    <div v-loading="userSolutionLoading" class="usersolution-container">
      <el-scrollbar>
        <el-container class="usersolution border-bottom" v-for="(v, key) in usersolution" :key="key">
          <el-aside width="40px" class="">
            <!-- <router-link v-slot="{ navigate }" custom :to="{ name: '用户', query: { userid: v.userid }, }">
              <el-avatar size="default" @click="navigate" :src="v.user?.headportrait"></el-avatar>
            </router-link> -->
            <el-avatar size="default" :src="v.user?.headportrait"></el-avatar>
          </el-aside>
          <el-main class="usersolution-content">
            <el-scrollbar>
              <header class="usersolution-content-header">
                <div class="username">
                  <span>
                    <!-- ID截取掉后两位替换为** -->
                    用户{{ getID(v.user?.ID) }}
                    <!-- {{ v.user?.name }} -->
                  </span>
                  <div class="usersolution-content-date font-size14">
                    <span v-text="TimeYH(v.createdAt)"></span>
                  </div>
                </div>
                <div class="usersolution-content-btn">
                  <div class="" v-if="v.user?.ID === user?.ID" :style="{ width: '60px' }">
                    <el-button size="default" type="primary" @click="update(v)" text bg>修改
                    </el-button>
                  </div>
                  <div class="" v-if="isAdmin" :style="{ width: '60px' }">
                    <el-button size="default" type="primary" @click="exportPdf(key)" bg>导出</el-button>
                  </div>
                </div>
              </header>
              <div :id="'usersolution-content-body-' + key" ref="usersolution_content_body">
                <el-scrollbar>
                  <div class="editor-content">
                    <div v-highlight v-html="v.context" class="editor-content-view font-size14"
                      @click="showImg($event)">
                    </div>
                  </div>
                </el-scrollbar>
                <pre v-highlight :class="'language-' + v.lang" class="code-pre-container">
                  <div v-if="showCopy" class="code-copy">
                    <div class="code-copy cursor-pointer" @click="myCopy(v.code || '')">
                      <el-icon class="icon">
                        <CopyDocument />
                      </el-icon>
                      <span class="font-size12">复制代码</span>
                    </div>
                  </div>
                  <code v-text="v.code" class="code-pre"/>
                </pre>
              </div>
            </el-scrollbar>
          </el-main>
        </el-container>
      </el-scrollbar>
    </div>
    <el-pagination class="pager" size="default" :page-size="limit" :total="totalCount"
      @current-change="(r) => (offset = limit * (r - 1))" layout="total,prev, pager, next"
      :current-page="Math.floor(offset / limit) + 1">
    </el-pagination>
    <div v-loading.fullscreen.lock="loading">
      <el-dialog v-model="dialogVisible" class="" title="提交题解" width="80%">
        <template #header>
          <span class="icon-text el-dialog__header-title">
            <el-icon class="text-primary">
              <Guide />
            </el-icon>
            提交题解
          </span>
        </template>
        <div class="title">
          <div class="title-desc">
            <span> 感谢您为这道题贡献题解！题解需有解题思路和题解代码，请勿抄袭题解。 </span>
            <br />
            <span> 为了保证题解质量，您提交的题解我们会在第一时间进行审核，通过后会展示在这里，为其他同学提供解题思路。 </span>
          </div>
          <div class="title-rule">
            <el-popover placement="left-start" :width="450" trigger="click" title="题解审核将根据以下规则：">
              <template #reference>
                <el-button class="" type="primary" size="default">
                  审核规则 &nbsp;
                  <el-icon :size="16">
                    <QuestionFilled />
                  </el-icon>
                </el-button>
              </template>
              <div class="rule-container">
                <ol>
                  <li class="rule-item">
                    <strong>思路详细：</strong>
                    <span>有详细解题思路，并能匹配提交代码的。</span>
                  </li>
                  <li class="rule-item">
                    <strong>格式明晰：</strong>
                    <span>编辑文本公式无错乱、源码格式无错乱等。</span>
                  </li>
                  <li class="rule-item">
                    <strong>内容与题解相关：</strong>
                    <span>求赞求转发而没有题解内容的不可以哦。</span>
                  </li>
                  <li class="rule-item">
                    <strong>无重复题解：</strong>
                    <span>当前公开题解中没有与提交题解完全一致的。</span>
                  </li>
                  <li class="rule-item">
                    <strong>未抄袭题解：</strong>
                    <span>抄袭本网站其他用户或其他网站题解。</span>
                  </li>
                </ol>
              </div>
              <!-- <div>
                <div>题解审核将根据以下规则：</div>
                <div>1）思路详细：有详细解题思路，并能匹配提交代码的；</div>
                <div>2）格式明晰：编辑文本公式无错乱、源码格式无错乱等；</div>
                <div>3）内容与题解相关：例如求赞求转发而没有题解内容的不可以哦；</div>
                <div>4）无重复题解：当前公开题解中没有与提交题解完全一致的；</div>
                <div>5）未抄袭题解：若抄袭本网站其他用户或其他网站题解</div>
                <div>如对某题目有疑问，可以添加网站右上角助教老师沟通。</div>
                <br>
                <div>每贡献一个题解并审核通过，+10贡献积分，+10金币。</div>
                <div>贡献积分会持续累加，不会消耗。</div>
              </div> -->
            </el-popover>

          </div>
        </div>
        <div class="content">
          <div class="wangEditor-container">
            <div>
              <label for="wangEditor" :style="{ height: '42px', lineHeight: '42px' }">解题思路 </label>
              <Wangeditor id="wangEditor" ref="wangEditor"
                v-bind="{ height: '420px', context: usersolutionfrom.htmlcontext, mode: 'simple' }">
              </Wangeditor>
            </div>
          </div>
          <div class="monaoEditor-container">
            <div>
              <label for="monaoEditor" :style="{ height: '42px', lineHeight: '42px' }">代码 </label>
              <el-select size="default" v-model="usersolutionfrom.lang" class="language-select" placeholder="请选择语言">
                <el-option label="C/C++" value="CPP" />
                <el-option label="Python" value="python" />
              </el-select>
            </div>
            <div>
              <MonaoEditor id="monaoEditor" ref="monaoEditor" :value="usersolutionfrom.code"
                v-bind="{ language: usersolutionfrom.lang, options: { minimap: { enabled: false, }, }, }"
                @change="change">
              </MonaoEditor>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="">
            <el-button size="default" @click="dialogVisible = false">取消</el-button>
            <el-button size="default" v-loading="loading" type="primary" @click="submit({ pid: null })">贡献题解</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 富文本中图片放大预览部分 -->
    <el-dialog v-model="imgShow" title="图片预览" align-center @click="imgShowHandler" :height="'100%'">
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          图片预览
        </span>
      </template>
      <el-image :src="previewImg" alt="" />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { QuestionFilled } from '@element-plus/icons-vue';
import { useClipboard } from '@vueuse/core';
import { ElMessage, ElMessageBox, ElPagination } from "element-plus";
import * as monaco from "monaco-editor";
import { assign } from "underscore";
import { computed, h, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import { asynccreatedorupdateusersolution, asyncselectteamuser, asyncselectusersolution } from "../../../api";
import MonaoEditor from "../../../components/MonaoEditor.vue";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { exportPdfFile } from "../../../util/pdf";
import { TimeYH } from '../../../util/time';
import Wangeditor from "../../components/wangeditor.vue";
const { text, copy, copied, isSupported } = useClipboard()

const props = defineProps<{
  ID?: number,
  user: Studycodemodel.Iuser,
  question?: Studycodemodel.Iquestion
}>()

const store = useStore(Storekey);
const getuser = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const teamId = computed(() => {
  return getuser.value?.teamid
})
const isAdmin = computed(() => {
  return getuser.value?.isAdmin
})

const dialogVisible = ref(false)

function update(v: Studycodemodel.Iusersolution) {
  Object.assign(usersolutionfrom, v)
  dialogVisible.value = true
}
const usersolutionfrom = reactive<Studycodemodel.Iusersolution>({
  context: '',
  htmlcontext: '',
  lang: 'CPP'
})

onMounted(() => {
  start()
  const v = localStorage.getItem(`usersolution_${props.ID}`)
  if (v) {
    const data = JSON.parse(v)
    Object.assign(usersolutionfrom, data)
  }
})
watch(() => props.ID, () => {
  localStorage.setItem(`usersolution_${props.ID}`, JSON.stringify(usersolutionfrom))
  start()
})

const offset = ref(0)
watch(() => offset.value, start)
const limit = ref(10)
const usersolution = ref<Studycodemodel.Iusersolution[]>([])
const totalCount = ref(0)
const userSolutionLoading = ref(false)
async function start() {
  try {
    userSolutionLoading.value = true
    // 团队成员
    const { rows, count } = await asyncselectteamuser({ teamid: teamId.value, })
    const userid = rows.map(e => e.userid)
    // userid,
    const data = await asyncselectusersolution({
      questionid: props.ID ? props.ID : 0,
      // userid,
      _limit: limit.value,
      _offset: offset.value,
      _order: ["top", "ID"],
      state: 1
    });
    totalCount.value = data.count;
    usersolution.value = data.rows;
    userSolutionLoading.value = false
  } catch (e: any) {
    userSolutionLoading.value = false
    console.error(e);
  }
  // nextTick(() => {
  //   highlight.highlightAll()
  // })
}

function change(v?: string, e?: monaco.editor.IModelContentChangedEvent) {
  if (e) {
    usersolutionfrom.code = v ? v : '';
  }
}

const wangEditor = ref()
const monaoEditor = ref()
const loading = ref(false)
const fullscreenLoading = ref(false)
async function submit({ pid }: any) {
  const editor: any = wangEditor.value;
  const html: string = editor.syncHTML();
  const text: string = editor.gettext();
  const htmlcontext: string = editor.getcontext();
  if (text.length < 5) {
    ElMessage.error("解题思路过少");
    return;
  }
  try {
    loading.value = true
    await asynccreatedorupdateusersolution(assign(usersolutionfrom, {
      pid,
      context: html,
      questionid: props.ID ? props.ID : 0,
      htmlcontext,
      text,
    }));
    ElMessage.success("提交成功");
    editor.removeNodes();
    usersolutionfrom.context = ''
    usersolutionfrom.code = ''
    usersolutionfrom.htmlcontext = ''
    loading.value = false
    ElMessageBox({
      title: '提交成功',
      message: h('p', null, [
        h('img', { src: 'https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/image/Banner_1', width: '488' }),
        h('span', null, '我们会在24小时内审核完成，通过后会进行公开展示。'),
        h('br', null, ''),
        h('br', {}, ''),
        h('span', {}, '贡献将按照以下规则：'),
        h('br', {}, ''),
        h('span', {}, '1）测试点正确：测试点需要完全符合题目要求、确保正确；'),
        h('br', {}, ''),
        h('span', {}, '2）测试点无重复：当前已有测试点中，没有完全重复或基本重复的测试点。'),
        h('br', {}, ''),
        h('span', {}, '3）内容与题解相关：例如求赞求转发而没有题解内容的不可以哦；'),
        h('br', {}, ''),
        h('span', {}, '4）无重复题解：当前公开题解中没有与提交题解完全一致的；'),
        h('br', {}, ''),
        h('span', {}, '5）未抄袭题解：若抄袭本网站其他用户或其他网站题解。'),
        h('br', {}, ''),
        h('br', {}, ''),
        // h('span', {}, '如对测试点有疑问，可以添加网站右上角助教老师沟通。'),

      ]),
      confirmButtonText: '好的',
      customStyle: {
        'width': '520px'
      },
      callback: () => {
        dialogVisible.value = false
      },
      buttonSize: 'default'
    })

  } catch (e: any) {
    loading.value = false
    ElMessage.error(e);
  }
  start();
}

// 判空,ID截取掉后两位替换为** 格式化ID，隐藏部分数字（默认显示前3位+3个*）
function getID(v: number | undefined): string {
  const visibleDigits = 3;  // 显示前几位
  const maskChar = '*';     // 替换字符
  const maskLength = 3;     // 替换数量
  if (!v) return "";
  const str = v.toString();
  return str.slice(0, visibleDigits) + maskChar.repeat(maskLength);
}

// 
const previewImg = ref("")
const imgShow = ref(false)
function showImg(e) {
  if (e.target.nodeName == 'IMG') {
    previewImg.value = e.target.currentSrc
    imgShow.value = true
  }
}
function imgShowHandler() {
  imgShow.value = false
}

function myCopy(str: string) {
  try {
    str ? copy(str) : '';
    ElMessage.success("复制成功");
  } catch (error) {
    console.error("myCopy error=>", str, error)
  }
}

const showCopy = ref(true)
const usersolution_content_body = ref<HTMLElement | null>(null)
function exportPdf(index: number) {
  userSolutionLoading.value = true;
  showCopy.value = false; // 隐藏复制按钮

  // 等待 DOM 更新完成后再执行导出操作
  nextTick(() => {
    const element = document.querySelector('#usersolution-content-body-' + index);
    console.log(element);
    exportPdfFile(element, `${props.question?.ID}-${props.question?.name}-题解`, () => {
      showCopy.value = true; // 恢复显示复制按钮
      userSolutionLoading.value = false;
    });
  });
}

</script>

<style scoped>
#discuss {
  --discuss-padding: 16px;
  padding: 0 var(--discuss-padding);

  --discuss-btn-height: 48px;
}

.discuss-btn {
  /* margin-bottom: var(--discuss-padding); */
  height: var(--discuss-btn-height);
  line-height: var(--discuss-btn-height);
  display: flex;
  align-items: center;
  justify-content: flex-end;
  /* padding-left: 12px; */
  /* font-size: 14px; */
  /* background: #f5f5f5; */
  /* border-radius: 2px; */
  /* color: #000; */
}

.usersolution-container {
  height: calc(100vh - 64px - var(--container-margin)* 4 - var(--el-tabs-item-height) - var(--discuss-btn-height) - var(--discuss-padding) - 32px - 2px);
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

.usersolution {
  margin-top: var(--container-margin);
  padding-bottom: var(--container-margin);
}

.usersolution-content {
  padding: 1px var(--discuss-padding);
}

.usersolution-content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px dashed rgb(222, 226, 230);
  padding-bottom: var(--container-margin);
}

.username {
  height: auto;
  display: flex;
  align-items: center;

  >span {
    font-weight: bolder;
    font-size: 16px;
    color: #8c8c8c;
    line-height: 24px;
  }
}

.usersolution-content-date {
  height: auto;
  display: flex;
  align-items: center;
}

.usersolution-content-date span {
  font-size: 13px;
  color: #8c8c8c;
  display: inline-block;
  margin-left: var(--container-margin);
}

.usersolution-content-btn {
  display: flex;
}

.editor-content {
  font-size: 14px;
  padding-top: var(--container-margin);
  /* margin: var(--container-margin) 0; */
}

.code-pre-container {
  display: flex;
  flex-direction: column;
}

.code-copy {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 28px;
}

.pager {
  margin: var(--container-margin);
  margin-right: 0;
  float: right;
}

.title {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}

.title-desc {}

.title-rule {}

.rule-container {}

.rule-item {
  line-height: 1.5rem;

  strong {
    color: #333;
  }

  span {
    color: #666;
  }
}

.content {
  display: flex;
}

.wangEditor-container,
.monaoEditor-container {
  width: 50%;
  margin: 6px;
}

.monaoEditor-container {}

#wangEditor,
#monaoEditor {
  margin: 6px 0;
}

.language-select {
  width: 200px;
  margin: 0 20px;
}

#monaoEditor {
  border: 1px solid rgb(204, 204, 204);
  height: 500px;
}
</style>

<style>
#discuss p {
  margin-bottom: 0px;
}

.slider-mouseover {
  border-left: 1px solid rgb(204, 204, 204);
}
</style>